﻿using System;
using System.Windows.Forms;
using System.IO;
using System.Collections;

namespace DataUpload
{
    public partial class FrmAddFiles : Form
    {
        private MainForm _container = null;
        private OpenFileDialog _ofdFiles;
        public const string FILTER
            = "All supporting formats (.txt, .csv, .xls, .xlsx, .mdb, .mdf) |*.txt;*.csv;*.xls;*.xlsx;*.mdb;*.mdf|"
            + "Flat files (.txt, .csv) |*.txt;*.csv|"
            + "Microsoft Excel (.xls, .xlsx) |*.xls;*.xlsx|"
            + "Microsoft Access (.mdb) |*.mdb|"
            + "Microsoft SQL Server (.mdf) |*.mdf";
        public readonly ArrayList SUPPORT_EXTENSION;

        public FrmAddFiles()
        {
            InitializeComponent();
        }

        public FrmAddFiles(MainForm container)
        {
            _container = container;
            InitializeComponent();

            SUPPORT_EXTENSION = new ArrayList();
            SUPPORT_EXTENSION.Add(".txt");
            SUPPORT_EXTENSION.Add(".csv");
            SUPPORT_EXTENSION.Add(".xls");
            SUPPORT_EXTENSION.Add(".xlsx");
            SUPPORT_EXTENSION.Add(".mdb");
            SUPPORT_EXTENSION.Add(".mdf");
        }

        private void btnNext_Click(object sender, EventArgs e)
        {
            if (dgvFiles.Rows.Count == 0)
            {
                MessageBox.Show("Select a file to continue!");
                return;
            }

            this.Hide();
            if (_container.frmBaseFormat == null)
                _container.frmBaseFormat = new FrmBaseFormat(_container);
            _container.frmBaseFormat.Show();
            _container.frmBaseFormat.Focus();
        }

        private void btnBack_Click(object sender, EventArgs e)
        {
            this.Hide();
            _container.frmConnect.Show();
            _container.frmConnect.Focus();
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            _container.Close();
        }

        /// <summary>
        /// Check whether a string exists in a DataGridView in selected column.
        /// </summary>
        /// <param name="findString">A string to look for, </param>
        /// <param name="source">A DataGridView to look in, </param>
        /// <param name="columnIndex">A column index to look in.</param>
        /// <returns>The row index found (-1 if given string not found).</returns>
        /// <remarks>If you want to look at every column in DataGridView, give columnIndex the value -1.</remarks>
        public static int FindStrGridView(string findString, DataGridView source, ref int columnIndex)
        {
            if (columnIndex != -1)
            {
                for (int i = 0; i < source.Rows.Count; i++)
                {
                    if (source[columnIndex, i].Value.ToString() == findString)
                        return i;
                }
                return -1;
            }

            for (columnIndex = 0; columnIndex < source.Columns.Count; columnIndex++)
            {
                for (int rowIndex = 0; rowIndex < source.Rows.Count; rowIndex++)
                {
                    if (source[columnIndex, rowIndex].Value.ToString() == findString)
                        return rowIndex;
                }
            }
            columnIndex = -1;
            return -1;
        }

        private bool CheckFileExtension(string filename)
        {
            for (int i = 0; i < SUPPORT_EXTENSION.Count; i++)
                if (filename.ToLower().EndsWith(SUPPORT_EXTENSION[i].ToString()))
                    return true;
            return false;
        }

        private void btnAddFiles_Click(object sender, EventArgs e)
        {
            _ofdFiles = new OpenFileDialog();
            _ofdFiles.Filter = FrmAddFiles.FILTER;
            _ofdFiles.InitialDirectory = Application.StartupPath;
            _ofdFiles.Multiselect = true;

            if (_ofdFiles.ShowDialog() == DialogResult.OK)
            {
                for (int i = 0; i < _ofdFiles.FileNames.Length; i++)
                {
                    int columnIndex = 1;
                    if (FrmAddFiles.FindStrGridView(_ofdFiles.FileNames[i], dgvFiles, ref columnIndex) == -1 &&
                        CheckFileExtension(_ofdFiles.FileNames[i]))
                    {
                        object[] rows = new object[3];
                        FileInfo fileInfo = new FileInfo(_ofdFiles.FileNames[i]);

                        if (_container.imgList.Images.IndexOfKey(fileInfo.Extension) == -1)
                            _container.imgList.Images.Add(fileInfo.Extension, System.Drawing.Icon.ExtractAssociatedIcon(_ofdFiles.FileNames[i]));

                        rows[0] = _container.imgList.Images[_container.imgList.Images.IndexOfKey(fileInfo.Extension)];
                        rows[1] = _ofdFiles.FileNames[i];
                        rows[2] = fileInfo.Length;

                        dgvFiles.Rows.Add(rows);
                    }
                }
            }
        }

        private void btnSort_Click(object sender, EventArgs e)
        {
            if (dgvFiles.SortedColumn == null || dgvFiles.SortedColumn.Index != 2)
            {
                System.ComponentModel.ListSortDirection direction = System.ComponentModel.ListSortDirection.Ascending;
                dgvFiles.Sort(dgvFiles.Columns[2], direction);
            }
        }

        private void btnMoveUp_Click(object sender, EventArgs e)
        {
            if (dgvFiles.Rows.Count < 2)
                return;

            if (dgvFiles.SelectedRows.Count > 1)
                dgvFiles.CurrentCell = dgvFiles.SelectedRows[0].Cells[1];

            int rowIndex = dgvFiles.CurrentRow.Index;
            DataGridViewRow currentRow = dgvFiles.CurrentRow;
            dgvFiles.Rows.RemoveAt(rowIndex);

            if (rowIndex - 1 >= 0)
                dgvFiles.Rows.Insert(rowIndex - 1, currentRow);
            else
                dgvFiles.Rows.Add(currentRow);
            
            dgvFiles.CurrentCell = dgvFiles[0, (rowIndex - 1 >= 0) ? rowIndex - 1 : dgvFiles.Rows.Count - 1];
            currentRow.Selected = true;
        }

        private void btnMoveDown_Click(object sender, EventArgs e)
        {
            if (dgvFiles.Rows.Count < 2)
                return;

            if (dgvFiles.SelectedRows.Count > 1)
                dgvFiles.CurrentCell = dgvFiles.SelectedRows[0].Cells[1];

            int rowIndex = dgvFiles.CurrentRow.Index;
            DataGridViewRow currentRow = dgvFiles.CurrentRow;
            dgvFiles.Rows.RemoveAt(rowIndex);

            if (rowIndex + 1 <= dgvFiles.Rows.Count)
                dgvFiles.Rows.Insert(rowIndex + 1, currentRow);
            else
                dgvFiles.Rows.Insert(0, currentRow);

            dgvFiles.CurrentCell = dgvFiles[0, (rowIndex + 1 < dgvFiles.Rows.Count) ? rowIndex + 1 : 0];
            currentRow.Selected = true;
        }

        private void btnRemoveFile_Click(object sender, EventArgs e)
        {
            if (dgvFiles.SelectedCells.Count > 0)
            {
                ArrayList rowIndex = new ArrayList();
                for (int i = 0; i < dgvFiles.SelectedCells.Count; i++)
                {
                    if (!rowIndex.Contains(dgvFiles.SelectedCells[i].RowIndex))
                        rowIndex.Add(dgvFiles.SelectedCells[i].RowIndex);
                }

                rowIndex.Sort();
                for (int i = rowIndex.Count - 1; i >= 0; i--)
                    dgvFiles.Rows.RemoveAt((int)rowIndex[i]);
            }
        }
    }
}
